<?php

class DrinkController extends ControllerBase
{
	public function init() {
            parent::init();
            $this->defaultAction = 'admin';
        }

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Drink;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Drink']))
		{
			$model->attributes=$_POST['Drink'];
                        $model->drinkprice = preg_replace('/\\s/', '', $_POST['Drink']['drinkprice']);
                        
                        $lastID = Util::generalTableID($model->tableName(), 'drinkid');
                        if ($lastID)
                            $model->drinkid = ++$lastID;
                        else
                            $model->drinkid = 0;
                        
                        $upload = CUploadedFile::getInstance($model, 'imgpath');
                        if ($upload != null)
                            $model->imgpath = $upload->name . "." . $upload->extensionName;
                        else
                            $model->imgpath = 'default';
                        
			if($model->save()){
                            if ($upload != null) {
                                $upload->saveAs(dirname(Yii::getPathOfAlias('webroot')) . "/" . SITE_FOLDER . "/uploads/images/menudrink/" . $upload->name . "." . $upload->extensionName);
                            }
                            
                            //add auto recipie for new drink
                            $recipie = new Recipie;
                            $lastID = Util::generalTableID('recipie', 'recipieid');
                            if ($lastID)
                                $recipie->recipieid = ++$lastID;
                            else
                                $recipie->recipieid = 0;
                            
                            $recipie->drinkid = $model->drinkid;
                            $recipie->active = 1;
                            $recipie->save();
                                                        
                            $this->setMessage('Create Drink Successful');
                            $this->refresh();
                        }
				
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}
        
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
                $oldImage = $model->imgpath;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Drink']))
		{
			$model->attributes=$_POST['Drink'];
                        $model->drinkprice = preg_replace('/\\s/', '', $_POST['Drink']['drinkprice']);
                        
                        $upload = CUploadedFile::getInstance($model, 'imgpath');
                        
                        if ($upload != null){
                            $upload->saveAs(dirname(Yii::getPathOfAlias('webroot')) . "/" . SITE_FOLDER . "/uploads/images/menudrink/" . $upload->name . "." . $upload->extensionName);
                            $model->imgpath = $upload->name . "." . $upload->extensionName;
                        }else
                            $model->imgpath = $oldImage;                            
                        
			if($model->save()){
                            $this->setMessage('Update Drink Successful');
                            $this->refresh();
                        }
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
//			$this->loadModel($id)->delete();
                        $recipie = Recipie::model()->find(array(
                            'condition' => 'drinkid = :id',
                            'params' => array(
                                ':id' => $id
                            )
                        ));
                        $recipie->active = 0;
                        $recipie->update('active');

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Drink('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Drink']))
			$model->attributes=$_GET['Drink'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Drink::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='drink-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
        
        public function actionGetMenuList(){
            $menuDrink = array();
            $menuSyrup = array();
            $menuDrinkType = array();
            $menuDrink = array();
            
            $drinktypes = Drinktype::model()->findAll();
            echo "<br/>";
            foreach ($drinktypes as $drinktype => $drinktypevalue){
                echo $drinktypevalue->drinktypeid." ".$drinktypevalue->drinktypename; 
                $menuDrinkType[$drinktypevalue->drinktypeid] = $drinktypevalue->drinktypename;
                
                $drinks = Drink::model()->findAll(array(
                    'condition' => 'drinktypeid = :drinktypeid',
                    'params' => array(
                        ':drinktypeid' => $drinktypevalue->drinktypeid,
                    )
                ));
                
                foreach ($drinks as $drink => $drinkvalue){
                    echo "&nbsp;&nbsp;&nbsp; ".$drinkvalue->drinkid." ".$drinkvalue->drinkname." ---------- ".$drinkvalue->drinkprice."<br/>";
                    $menuDrink[$drinkvalue->drinkid] = array(
                        $drinkvalue->drinkname => $drinkvalue->drinkprice,
                    );
                    
                    $recipies = Recipie::model()->findAll(array(
                        'condition' => 'drinkid = :drinkid',
                        'params' => array(
                            ':drinkid' => $drinkvalue->drinkid,
                        )
                    ));                    
                }
                $menuDrinkType[$drinktypevalue->drinktypeid] = $menuDrink;
                unset($menuDrink);
                                
                $syrups = Syrup::model()->findAll(array(
                    'condition' => 'drinktypeid = :drinktypeid',
                    'params' => array(
                        ':drinktypeid' => $drinktypevalue->drinktypeid,
                    )
                ));
                if (count($syrups)){
                    foreach ($syrups as $syrup => $syrupvalue){
//                        echo $syrupvalue->syrupname." ".$syrupvalue->syrupprice."<br/>";
                        $menuSyrup[$syrupvalue->syrupid] = array(
                            $syrupvalue->syrupname => $syrupvalue->syrupprice,
                        );
                    }
                }
            }
            $menuDrink['drink'] = $menuDrinkType;
            $menuDrink['syrup'] = $menuSyrup;
            echo CJSON::encode($menuDrink);
//            var_dump($menuDrinkType);
//            echo "<pre>"; print_r($menuDrink); echo "</pre>";
            
        }
        
        public function actionMaterialRequest(){
            
        }
}
